package com.spark.jasypt;

import org.jasypt.encryption.StringEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.core.env.Environment;

/**
 * 加密密钥不要写在配置文件中
 * 方式一：直接作为程序启动时的命令行参数来带入
 * java -jar yourproject.jar --jasypt.encryptor.password=CodeSheep
 * 方式二：直接作为程序启动时的应用环境变量来带入
 * java -Djasypt.encryptor.password=CodeSheep -jar yourproject.jar
 * 方式三：甚至可以作为系统环境变量的方式来带入
 * 比方说，我们提前设置好系统环境变量JASYPT_ENCRYPTOR_PASSWORD = CodeSheep，则直接在Spring Boot的项目配置文件中做如下配置即可：
 * jasypt.encryptor.password=${JASYPT_ENCRYPTOR_PASSWORD:}
 *
 *
 * https://www.toutiao.com/i6819460523768152583/
 */
@SpringBootApplication
public class JasyptApplication implements CommandLineRunner {

    @Autowired
    private ApplicationContext applicationContext;

    @Autowired
    private StringEncryptor jasyptStringEncryptor;

    public static void main(String[] args) {
        SpringApplication.run(JasyptApplication.class, args);
    }

    /**
     * 初始可以调用下面的方法来进行生成加密后的字符串，
     */
    @Override
    public void run(String... args) throws Exception {

        /*Environment environment = applicationContext.getBean(Environment.class);

        // 首先获取配置文件里的原始明文信息
        String mysqlOriginPswd = environment.getProperty("spring.datasource.password");
        String redisOriginPswd = environment.getProperty("redis.password");
        String aliSmsOriginAk = environment.getProperty("ali.sms.access_key_secret");

        // 加密
        String mysqlEncryptedPswd = encrypt(mysqlOriginPswd);
        String redisEncryptedPswd = encrypt(redisOriginPswd);
        String aliSmsEncryptedAk = encrypt(aliSmsOriginAk);

        // 打印加密前后的结果对比
        System.out.println("MySQL原始明文密码为：" + mysqlOriginPswd);
        System.out.println("Redis原始明文密码为：" + redisOriginPswd);
        System.out.println("阿里云SMS原始AccessKey密码为：" + aliSmsOriginAk);
        System.out.println("====================================");
        System.out.println("MySQL原始明文密码加密后的结果为：" + mysqlEncryptedPswd);
        System.out.println("Redis原始明文密码加密后的结果为：" + redisEncryptedPswd);
        System.out.println("阿里云SMS原始AccessKey密码加密后的结果为：" + aliSmsEncryptedAk);*/
    }

    private String encrypt(String originPassord) {
        return jasyptStringEncryptor.encrypt(originPassord);
    }

    private String decrypt(String encryptedPassword) {
        return jasyptStringEncryptor.decrypt(encryptedPassword);
    }
}
